package com.fz.song.interceptor;


import com.fz.song.common.Constants;
import com.fz.song.enums.ExceptionEnum;
import com.fz.song.exception.CustomException;
import com.fz.song.pojo.SysResource;
import com.fz.song.pojo.SysUser;
import com.fz.song.service.RoleService;
import com.fz.song.service.UserService;
import com.fz.song.util.CookieUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.List;

import static com.fz.song.util.CookieUtil.getMD5;


public class WebInterceptor extends HandlerInterceptorAdapter {
    private static Logger log = Logger.getLogger(WebInterceptor.class);
    //登录,注册
    private static String[] nologin_filter_uri = new String[]{"/login", "/register", "/userlogin", "/authcode"};

    @Autowired
    public UserService userService;
    @Autowired
    public RoleService roleService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String requestURI = request.getRequestURI();
        if (handler instanceof HandlerMethod) {
            HandlerMethod authhandler = (HandlerMethod) handler;
            printHTTP(request, authhandler);
        }

        HttpSession session = request.getSession();
        SysUser user = (SysUser) session.getAttribute(Constants.LOGIN_USER);
        if (user == null) {
            autoLogin(request, response, session, user);
        }


        //不用登录的直接放行
        if (isLogin(request) || isNoNeedLoginURL(requestURI)) {
            if (requestURI.endsWith("login")) {
                if (isLogin(request)) {
                    response.sendRedirect(request.getContextPath() + "/index");// 未登录用户跳转到登陆页
                    return false;
                } else {
                    return true;
                }
            } else {
                return true;
            }
        } else {
            String contextPath = request.getContextPath() + "/login";
            response.sendRedirect(contextPath);// 未登录用户跳转到登陆页
            return false;
        }
    }

    private void autoLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session, SysUser user) throws CustomException {

        String[] cookieValues = CookieUtil.readCookie(request, response);
        if (cookieValues != null) {
            String loginname = cookieValues[0];
            user = userService.getUserByLoginName(loginname);
            if (user != null) {
                String password = user.getPassword();
                String validTimeInCookie = cookieValues[1];
                String md5ValueInCookie = cookieValues[2];
                String md5ValueFromUser = getMD5(user.getLoginname() + ":" + user.getPassword() + ":" + validTimeInCookie + ":" + Constants.WEB_KEY);
                //将结果与Cookie中的MD5码相比较,如果相同,写入Session,自动登陆成功,并继续用户请求
                if (md5ValueFromUser.equals(md5ValueInCookie)) {
                    loginAfter(request, response, session, user);
                }
            } else {
                ExceptionEnum userNotExists = ExceptionEnum.USER_NOT_EXISTS;
                throw new CustomException(userNotExists.getCode(), userNotExists.getMessage());
            }
        }

    }

    public void loginAfter(HttpServletRequest request, HttpServletResponse response, HttpSession session, SysUser sysUser) {
        session.setAttribute(Constants.LOGIN_USER, sysUser);
        session.setMaxInactiveInterval(60 * 30);
        //处理权限信息

        //加载我的待办

        //加载我的菜单
        Integer userid = sysUser.getSysid();
        //获取我的角色
        List<SysResource> userRoles = roleService.getMyResource(userid);

        List<SysResource> onelist = new ArrayList<SysResource>();
        //定义一个一级目录
        List<SysResource> twolist = new ArrayList<SysResource>();
        //定义一个二级目录

        for (SysResource resource : userRoles) {
            String type = resource.getType();
            if (Constants.MENU_MODULE.equals(type)) {
                onelist.add(resource);
            } else {
                twolist.add(resource);
            }
        }

        for (SysResource one : onelist) {
            Integer sysid = one.getSysid();
            for (SysResource two : twolist) {
                Integer pid = two.getPid();
                if (sysid == pid) {
                    one.getChilds().add(two);
                }
            }
        }
        session.setAttribute("menuinfo", onelist);

        //加载我的消息
    }

    private boolean isLogin(HttpServletRequest request) {
        Object obj = request.getSession().getAttribute(Constants.LOGIN_USER);
        return (null != obj);
    }

    private boolean isNoNeedLoginURL(String url) {

        for (String nourl : nologin_filter_uri) {
            if (url.endsWith(nourl)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 打印请求信息
     *
     * @param request
     * @param handler1
     * @author zhanghui
     * @time 2016-3-2下午5:32:32
     */
    public static void printHTTP(HttpServletRequest request, HandlerMethod handler1) {
        // 打印请求情况
        log.info("--------------------- Request Start ------------------------");
        log.info("请求 URL：" + request.getRequestURI());
        log.info("控制器类：" + handler1.getBeanType().getName());
        log.info("页面URL类方法名：" + handler1.getMethod().getName());
        log.info("--------------------- Request End --------------------------\n");
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
